package main

import (
	"fmt"
	"github.com/giorgisio/goav/avcodec"
	"github.com/giorgisio/goav/avformat"
	//"github.com/giorgisio/goav/avutil"
)

func main() {

	var ret int =1

	var ictx *avformat.Context
	var octx *avformat.Context

	iurl := "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"
	ourl := "rtmp://localhost:1935/live/movie"

	//var starttime int64

	avformat.AvRegisterAll()

	ret = avformat.AvformatNetworkInit()

	if ret < 0 {
		fmt.Println("Network init error")
	}

	ret = avformat.AvformatOpenInput(&ictx,iurl,nil,nil)

	if ret < 0 {
		fmt.Println("Open Input error")
	}

	ret = avformat.AvformatFindStreamInfo(ictx,nil)

	if ret < 0 {
		fmt.Println("Stream Info error")
	}

	ictx.AvDumpFormat(0,iurl,0)


	ret = avformat.AvformatAllocOutputContext2(&octx,avformat.AvGuessFormat("","t.flv",""),"",ourl)

	if ret < 0 {
		fmt.Println("Output Context Error")
	}

	for _, v := range ictx.Streams() {
		/*
		if v.Codec().GetCodecType() == avformat.AVMEDIA_TYPE_VIDEO {
			fmt.Println("video stream get")
			i_video_stream = v
			break
		}
		*/
		
		var ostream *avformat.Stream = octx.AvcodecNewStream(avcodec.AvcodecFindEncoder(v.CodecParameters().AvCodecGetId()))
		if ostream == nil {
			fmt.Println("ostream is nil")
		}
		ret = avcodec.AvcodecParametersCopy(ostream.CodecParameters(),v.CodecParameters())

		if ret < 0 {
			fmt.Println("parameters copy error")
		}

		ostream.CodecParameters().AvCodecSetType(0)

	}

	octx.AvDumpFormat(0,ourl,1)

	res := avformat.AvIOOpenTo(octx.Pb(),ourl,avformat.AVIO_FLAG_WRITE)

	if res != nil {
		fmt.Println("io Open Error")
	}
	fmt.Println("AvformatWriteHeader")
	ret = octx.AvformatWriteHeader(nil)
	
	if ret < 0 {
		fmt.Println("write header error")
	}


	//var starttime int64 = avcodec.AvGettime()

	for true {
		var pkt *avcodec.Packet
		ret = ictx.AvReadFrame(pkt)

		if ret >= 0 {
			
			var itime avcodec.Rational = ictx.Streams()[pkt.StreamIndex()].TimeBase()
			var otime avcodec.Rational = octx.Streams()[pkt.StreamIndex()].TimeBase()
			pkt.SetPts(avcodec.AvRescaleQRnd(pkt.Pts(),itime,otime))
			pkt.SetDts(avcodec.AvRescaleQRnd(pkt.Dts(),itime,otime))
			pkt.SetDuration(avcodec.AvRescaleQRnd(pkt.Duration(),itime,otime))
			pkt.SetPos(-1)

			octx.AvInterleavedWriteFrame(pkt)

		} else {
			fmt.Println("read frame error")
		}

	}


	







}